package com.uwantsoft.interfaces.web.controller.web;

import com.uwantsoft.business.facade.UserFacadeImpl;
import com.uwantsoft.business.facade.dto.user.UserDto;
import com.uwantsoft.business.facade.dto.user.UserOverviewQueryCondition;
import com.uwantsoft.util.paging.DefaultPaginatedList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @Author peichen
 */
@Controller(value = "backendUserController")
@RequestMapping(value = "/backend")
public class UserController {

    @Resource(name = "userFacade")
    private UserFacadeImpl userFacade;

    @RequestMapping(value = "useroverview")
    public String obtainAllUser(UserOverviewQueryCondition userOverviewQueryCondition,Model model) {
        DefaultPaginatedList defaultPaginatedList = userFacade.obtainUserByPage(userOverviewQueryCondition);
        model.addAttribute("defaultPaginatedList", defaultPaginatedList);
        return "backend/useroverview";
    }

    @RequestMapping(value = "user")
    public String addOrUpdateUser(@Valid UserDto userDto,BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return "backend/userform";
        }
        userFacade.createOrUpdateUser(userDto);
        return "redirect:useroverview";
    }

    @RequestMapping(value = "userform")
    public String userForm(String guid, Model model) {
        UserDto userDto = userFacade.obtainUser(guid);
        model.addAttribute("userDto", userDto);
        return "backend/userform";
    }

    @RequestMapping(value = "delete")
    public String deleteUser(String guid) {
        userFacade.deleteUser(guid);
        return "redirect:useroverview";
    }
}

